<template>
  <div id='wrap'>
    <h1>effectScope案例2</h1>
    <button @click="runtimerlScope">runtimer1Scope</button>
    <button @click="stoptimerlScope">stoptimer1Scope</button>
    <hr>
    <button @click="runtimer2lScope">runtimer2lScope</button>
    <button @click="stoptimer2lScope">stoptimer2lScope</button>
    <hr>
    <button @click="ganR">干扰2000+</button>
  </div>
</template>

<script lang='ts'>
export default {
  name: 'scu7',
}
</script>

<script lang='ts' setup>
import { ref,type Ref,reactive,effectScope,onScopeDispose, EffectScope } from 'vue'
function userTimer():EffectScope {
    const scope=effectScope()
    return scope
}
function srun(scope:EffectScope,stop=1000):{time:Ref<number>} {
    const time=ref(0)
    let interval:ReturnType<typeof setInterval>
        scope.run(()=>{
            interval=setInterval(() => {
                console.log(time.value);
                time.value++
            }, stop);
            onScopeDispose(()=>{
                clearInterval(interval)
                console.log('计时器停止');
            })
        })
        return {time}
}
const rac=reactive<Ref<number>[]>([])
const time1=userTimer()
const runtimerlScope=()=>{
    const {time} = srun(time1)
    rac.push(time)
}
const stoptimerlScope=()=>{
    time1.stop()
}
const time2=userTimer()
const runtimer2lScope=()=>{
    const {time} = srun(time2)
    rac.push(time)
    console.log(rac);
    
}
const stoptimer2lScope=()=>{
    time2.stop()
}
const ganR=()=>{
    if(rac.length>0){
        rac[0].value=2000
    }
}
</script>

<style scoped lang='scss'>

</style>